<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\enum\account\PayeeType;
use app\common\enum\account\PaymentPayeeType;
use app\common\enum\order\PayType;
use app\common\exception\BaseException;
use app\common\model\AccountRecord;
use app\common\model\Dealer;
use app\common\model\ReceiveLog;
use app\common\model\Salesman;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\AccountPaymentRecord;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="收款单")
 */
class AccountPayment extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new AccountPaymentRecord();
        $this->each  = true;
    }

    public function amount(): Json
    {
        $get = $this->request->get();
        if (empty($get['payee_id']) && empty($get['payee_type'])) return $this->error('请选择支付类型和收款方ID');
        $model  = new AccountRecord();
        $amount = $model->where('company_id', $this->companyId)
                        ->where('payee_type', $get['payee_type'])
                        ->where('payee_id', $get['payee_id'])
                        ->value('submit_money');
        return $this->success(['amount' => $amount]);
    }

    public function each($list)
    {
        return $list->each(function ($item)
        {
            // 处理人
            $item->handler = $item->handler()->value('username');
            if ($item->payee_type == PaymentPayeeType::SALES) {
                $item->payee_name = $item->salesman()->value('rename');
            } elseif ($item->payee_type == PaymentPayeeType::DRIVER) {
                $item->payee_name = $item->driver()->value('name');
            } else {
                $item->payee_name = '未知';
            }
            if ($item->store_id) {
                $item->store_name = $item->store()->value('name');
            }
        });
    }

    /**
     * @NodeAnnotation (title="新增")
     * @throws BaseException
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $this->sceneValidate($post, 'add');
        $post['company_id'] = $this->companyId;
        $post['handler_id'] = $this->uid;
        $post['no']         = generateOrderNo('SK');
        try {
            $this->model->transaction(function () use ($post)
            {
                //更新对款单信息数据
                $accountRecord = AccountRecord::where(['payee_id' => $post['payee_id'], 'payee_type' => $post['payee_type']])
                                              ->find();
                if (!$accountRecord) throw new BaseException(['message' => '对账单信息不存在']);
                $post['account_id'] = $accountRecord->id;
                $post['status']     = 2;
                $post['pay_type']   = PayType::CASH;
                if($post['payee_type'] == PayeeType::SALESMAN){
                    $payee_name = Salesman::where('id',$post['payee_id'])->value('rename');
                }else if($post['payee_type'] == PayeeType::DEALER){
                    $payee_name = Dealer::where('id',$post['payee_id'])->value('name');
                }
                $post['payee_name'] = $payee_name ?? '';
                $this->model->save($post);
                $accountRecord->dec('submit_money', $post['amount'])->inc('real_money', $post['amount'])->save();
                //更新交易明细状态
                $receiveLog = ReceiveLog::where(['payee_id' => $post['payee_id'], 'payee_type' => $post['payee_type'], 'pay_type' => PayType::CASH])
                                        ->find();
                if (!$receiveLog) throw new BaseException(['message' => '交易明细信息不存在']);
                (new ReceiveLog())->where(['payee_id' => $post['payee_id'], 'payee_type' => $post['payee_type'], 'pay_type' => PayType::CASH])
                                  ->save([
                                                 'status'     => 2,
                                                 'check_time' => time()
                                         ]);
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }

    /**
     * @NodeAnnotation (title="审核")
     */
    public function check(Request $request, $id): Json
    {
        $this->checkPost();
        $post = $request->post();
        $row  = $this->model->find($id);
        if (!$row) return $this->error('数据不存在');
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                //更新对款单信息数据
                $accountRecord = AccountRecord::where(['payee_id' => $row->payee_id, 'payee_type' => $row->payee_type])
                                              ->find();
                if (!$accountRecord) throw new BaseException(['message' => '对账单信息不存在']);
                $row->save([
                                   'trade_no'   => $post['trade_no'],
                                   'account_id' => $accountRecord->id,
                                   'status'     => 2,
                           ]);
                //更新对款单信息数据
                $accountRecord->dec('check_money', $row->amount)->inc('real_money', $post['amount'])->save();
                //更新交易明细状态
                $receiveLog = ReceiveLog::where(['payee_id' => $post['payee_id'], 'payee_type' => $post['payee_type'], 'store_id' => $row->store_id, 'pay_type' => PayType::BANK])
                                        ->find();
                if (!$receiveLog) throw new BaseException(['message' => '交易明细信息不存在']);
                (new ReceiveLog())->where(['payee_id' => $post['payee_id'], 'payee_type' => $post['payee_type'], 'store_id' => $row->store_id, 'pay_type' => PayType::BANK])
                                  ->save([
                                                 'status'     => 2,
                                                 'check_time' => time()
                                         ]);
            });
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }


}
